<!DOCTYPE html>
<html >
    <head>
        <meta charset="UTF-8">
        <title>图片跟随鼠标移动</title>
        <style>
            *{
                padding: 0;
                margin: 0;
            }
            img{
                border: 0 none;
            }
        </style>
        <script>
            //鼠标的坐标定义的变量
                var mx,my;
            //定义div对象
                var ad,bar;
            //定义一个被拖动的对象
                var drag;
            //定义鼠标点到div定点的偏移量
            var pl = 0;
            var pt = 0;

            window.onload = function () {
                ad  = document.getElementById("ad");
                bar  = document.getElementById("ad");
                //div在鼠标按下的时候
                ad.onmousedown = function () {
                    drag = true;//  drag = 1;
                };
                //div在鼠标按下的时候
                ad.onmouseup = function () {
                    drag = false;//  drag = 0;
                };



                //div在鼠标按下的时候
                bar.onmousedown = function (a) {
                    //鼠标的坐标
                    var cx = a.clientX? a.clientX:a.layerX;
                    var cy = a.clientY? a.clientY:a.layerY;

                    //div 的坐标
                    var dx = parseInt(ad.style.left);
                    var dy = parseInt(ad.style.top);
                    //偏移量
                    pl = cx - dx;
                    pt = cy - dy;

                    drag = 1;
                };
                //div在鼠标按下的时候
                bar.onmouseup = function () {
                    drag = 0;//  drag = 0;
                };
            };
            //if (boolean)   if (4)
            //条件表达式    把条件表达式的结果 强制转化为boolean
            //只要条件表达式的内容不为0，就是true，0或者undefined  \ '' \null   就是false

          //onmouseover鼠标悬停  onmousemove鼠标移动
          document.onmousemove = function (e) {
              //控制台   输出鼠标坐标 事件对象的属性 clienx[layerx]  clieny[layery]
                //console.info(mx+":"+my);
                /*
                三元运算符  boolear?x:y
                */

                mx  = e.clientX? e.clientX :e.layerX;
                my  = e.clientY? e.clientY :e.layerY;
                //div 的坐标
                if(drag){
                    ad.style.left = mx - pl+ "px";
                    ad.style.top =my - pt+ "px";
                }


          };
/*var sex = 1;
alert(sex?'男':'女');*/
        </script>
    </head>
    <body>
        <div id="ad" style="position: absolute;width: 200px;height: 200px;border: 1px solid #c1bec0;left: 0;top: 0">
            <div id="bar" style="height: 40px;cursor:move;line-height: 40px;background-color: #2fab3c">标题栏</div>
        </div>
    </body>
</html>